#!/bin/bash
. ${ATLASEDGE_SOFTWARE_PATH}/edge_site/edge_manager/src/script/common.sh
. ${ATLASEDGE_SOFTWARE_PATH}/edge_site/edge_manager/src/script/log_util.sh

CUR_DIR=$(dirname $(readlink -f $0))
CFG_PATH=$ATLASEDGE_CONFIG_PATH
SFT_PATH=$ATLASEDGE_SOFTWARE_PATH
CORE_PATH=${SFT_PATH}/edge_core
BACKUP_PATH=${CFG_PATH}/backup

function showHelp()
{
    local fileName=`basename $0`
    echo -e "
*********************************************************************************************
Usages:  [cmd] [options] [values]
    -mode   install mode                full, typical or simple
                                        default is full mode
                                        in band systems should be full mode, 200 Soc typical 
                                        mode, and BMC system simple mode
    -log    log path                    input log dir(should be absolute path)
                                        default is /var/plog/kube_edge
    -help   show help                   none
Notes: 
    If some option is not set, default settings will be token

Examples:
    ./${fileName}
    ./${fileName} -mode full -log /var/alog/AtlasEdge
*********************************************************************************************
"
    return 0
}

function prepareIEF()
{
    # now /opt/edge_*
    if [ -L /opt/edge-installer ];then
        rm -rf /opt/edge-installer
        logger_Info "rm ief installer"
    fi
    if [ -L /opt/edge-register ];then
        rm -rf /opt/edge-register
        logger_Info "rm ief register"
    fi

    mkdir -p /opt/edge-installer
    mkdir -p /opt/edge-register
    cp -rf ${SFT_PATH}/IEF/edge-installer/* /opt/edge-installer
    cp -rf ${SFT_PATH}/IEF/edge-register/* /opt/edge-register
    cp ${SFT_PATH}/IEF/edge-installer/encrypt_tool /opt/edge-register/

    mkdir -p  /var/lib/FD/kubelet/device-plugins

    logger_Info "prepare ief finished"
}

function start_IEF()
{
    cat "${CFG_PATH}/NODE_INFO" | grep net_manager | grep IEF
    if [ $? -eq 0 ];then
        # edge core running
        local iefActive="`systemctl is-active edgecore.service 2>/dev/null`"
        local iefEnable="`systemctl is-enabled edgecore.service 2>/dev/null`"
        if [ "${iefEnable}" == "enabled" -a "$iefActive" == "active" ];then
            logger_Info "IEF edge_core running now"
        else
            # ief installed but not running
            if [ -f /opt/IEF/Edge-core/script/install/edgecore.service ];then
                logger_Info "IEF edge_core installed"
            else
                # ief not installed
                LOG_PATH=`ReadINIfile ${CFG_PATH}/config.ini SYS log_path`
                if [ ! -f "/run/web/ief_cert.tar.gz" ];then
                    logger_Error "ief cert not prepared"
                fi
                ${SFT_PATH}/edge_site/edge_manager/src/script/ief_launch.sh "${LOG_PATH}" "/run/web/ief_cert.tar.gz" "FD_IEF" \
                    "node.MQTT_INTERNAL=tls://127.0.0.1:8889;node.INSTALL_MODE=IEF;node.UNINSTALL_CLEAN=true;node.SKIP_NODE_TYPE=true" >/dev/null 2>&1
                if [ $? -ne 0 ];then
                    logger_Error "call ief_launch failed"
                fi
                rm -rf /opt/Atlastmp/IEF/
                sleep 1
                iefActive="`systemctl is-active edgecore.service 2>/dev/null`"
                iefEnable="`systemctl is-enabled edgecore.service 2>/dev/null`"
                if [ "${iefEnable}" == "enabled" -a "$iefActive" == "active" ];then
                    logger_Info "IEF edge_core running now"
                fi
                rm -rf /run/web/ief_cert.tar.gz
            fi
        fi
    fi
    return 0
}

function checkFdBackupCert()
{
    if [ ! -e ${CORE_PATH}/certFD/FD.crt ] || [ ! -e ${CORE_PATH}/certFD/FD_Backup.checksum ]; then
        logger_Info "FD backup cert file not exist."
        return 1
    fi

    sha256sum -c ${CORE_PATH}/certFD/FD_Backup.checksum
    if [ $? -ne 0 ]; then
        logger_Error "Check FD backup cert fail."
        return 1
    fi
    
    return 0
}

function checkFdWorkCert()
{
    certPath=$1
    if [ ! -e ${certPath}/FD.crt ] || [ ! -e ${CORE_PATH}/certFD/FD_Work.checksum ]; then
        logger_Info "FD work cert file not exist."
        return 1
    fi

    sha256sum -c ${CORE_PATH}/certFD/FD_Work.checksum
    if [ $? -ne 0 ]; then
        logger_Error "Check FD work cert fail."
        return 1
    fi
    
    return 0
}

function resumeFdCert()
{
    checkFdBackupCert
    if [ $? -ne 0 ]; then
        logger_Info "check back fd cert fail."
        return 1
    fi

    fdCertPath=$1
    cp -f ${CORE_PATH}/certFD/FD.crt ${fdCertPath}
    logger_Info "Resume backup fd cert success."    
    sha256sum ${fdCertPath}/FD.crt > ${CORE_PATH}/certFD/FD_Work.checksum
    return $?
}

function backupFdCert()
{
    checkFdBackupCert
    if [ $? -eq 0 ]; then
        return 0
    fi

    logger_Info "backup fd cert check fail, need resume back fd cert."
    fdCertPath=$1
    cp -f ${fdCertPath}/FD.crt ${CORE_PATH}/certFD/  
    sha256sum ${CORE_PATH}/certFD/FD.crt > ${CORE_PATH}/certFD/FD_Backup.checksum
    return
}

function checkAndResumeFdCert()
{
    fdCertFilePath=$(get_cert_dir)

    checkFdWorkCert ${fdCertFilePath}
    if [ $? -eq 0 ]; then
        logger_Info "Check FD cert success."
        backupFdCert ${fdCertFilePath}
        return
    fi

    logger_Info "Check FD cert fail, resume backup fd cert."
    resumeFdCert ${fdCertFilePath}
}

# cp files to dst dir
function prepare()
{
    # database of edgecore.yaml
    sed -i "s!dataSource:[^)]*!dataSource: ${CFG_PATH}/edge.db!g" ${CORE_PATH}/conf/edgecore.yaml
    # add dataSourceDamaged, dataBak config to line 3, 4
    if [ ! -d ${BACKUP_PATH} ]; then
      mkdir -p ${BACKUP_PATH}
    fi
    sed -i "s!dataSourceDamaged:[^)]*!dataSourceDamaged: ${BACKUP_PATH}/edge.db.damaged!g" ${CORE_PATH}/conf/edgecore.yaml
    sed -i "s!dataBak:[^)]*!dataBak: ${BACKUP_PATH}/edge.db.bak!g" ${CORE_PATH}/conf/edgecore.yaml

    # set cgroup driver type
    cgroupsDriver=`docker info 2>/dev/null | grep 'Cgroup Driver' | awk '{print $3}'`
    if [ "$cgroupsDriver" != "" ];then
        sed -i "s|cgroupDriver:.*|cgroupDriver: ${cgroupsDriver} |g" ${CORE_PATH}/conf/edgecore.yaml
    fi

    update_interface_name ${CORE_PATH}/conf/edgecore.yaml

    # fill asset tag file
    cat $CFG_PATH/default_capability.json  | grep esp_enable | grep true
    if [ $? == 0 -a -f /run/elabel_info ];then
        asset_tag=`cat /run/elabel_info | grep "extend_info" | awk '{print $2}'`
        echo ${asset_tag} > $CFG_PATH/asset_tag
    fi

    checkAndResumeFdCert
    
    # wait for miniD active (500)
    i=0
    while [ $i -le 30 ]
    do
        if [ ! -f /home/data/upgrade/minidactive ];then
            logger_Info "detected active file not exit"
            break
        fi
        let i++
        sleep 1
    done

}

function startAtlasedge()
{
    bind_port_uid ${CORE_PATH}/conf/edgecore.yaml

    # start atlasEdge
    logger_Info "start to run Edgecore"
    LOG_PATH=`ReadINIfile ${CFG_PATH}/config.ini SYS log_path`
    logger_Info " preCheck OK LOG_PATH:" $(basename ${LOG_PATH})

    cat "${CFG_PATH}/NODE_INFO" | grep net_manager | grep IEF >/dev/null
    if [ $? -ne 0 ];then
        logger_Info "NetManager is not IEF"

        ${SFT_PATH}/libs/ld-linux-aarch64.so.1 --library-path ${SFT_PATH}/libs/ ${CORE_PATH}/edge_core >> $LOG_PATH/edge_core.log 2>&1 &
        if [ $? -ne 0 ];then
            logger_Error "install edgecore failed"
        else
            docker load -i ${CORE_PATH}/pause-atlas.tar.gz
            if [ ! $? -eq 0 ];then
                logger_Error "load pause-atlas.tar.gz failed"
            else
                logger_Info "install edge_core success"
            fi
        fi
        # wait for edge core starting finish
        sleep 1

        # container restart fails after reboot sometimes
        container=$(docker ps -a  | grep k8s_POD | cut -d " " -f1)
        if [ -n "$container" ]; then
            docker start $container
        fi

        if [ -f ${CORE_PATH}/AscendK8sDevicePlugin ];then
            if [ ! -f "${CFG_PATH}/DoubleManagerMode" ];then
                ps -ef | grep AscendK8sDevicePlugin | grep -v grep
                if [ $? -ne 0 ];then
                    ${SFT_PATH}/libs/ld-linux-aarch64.so.1 --library-path ${SFT_PATH}/libs/:/usr/lib64 ${CORE_PATH}/AscendK8sDevicePlugin --mode=ascend310 --fdFlag=true --useAscendDocker=false 1>/dev/null 2>&1 &
                    logger_Info "start AscendK8sDevicePlugin success"
                fi
            fi
        else
            logger_Warn "start AscendK8sDevicePlugin failed. ${CORE_PATH}/AscendK8sDevicePlugin not exist"
        fi

        # if not DualManagerMode ,exit
        if [ ! -f "${CFG_PATH}/DoubleManagerMode" ];then
            exit 0
        fi	
    else
        logger_Info "NetManager is IEF"
    fi
    
    #add systemctl service for edge
    if [ -f /opt/IEF/Edge-core/script/install/edgecore.service ];then
        if [ ! -f /lib/systemd/system/edgecore.service ];then
            cp /opt/IEF/Edge-core/script/install/edgecore.service /lib/systemd/system/
            systemctl enable edgecore.service
            systemctl start edgecore.service
            logger_Info "edgecore start"
        fi
    fi
    if [ -f /opt/IEF/Edge-core/script/install/edgeinstaller.service ];then
        if [ ! -f /lib/systemd/system/edgeinstaller.service ];then
            cp /opt/IEF/Edge-core/script/install/edgeinstaller.service /lib/systemd/system/
            systemctl enable edgeinstaller.service
            systemctl start edgeinstaller.service
            logger_Info "edgeinstaller start"
        fi
    fi
    if [ -f /opt/IEF/Edge-logger/script/install/edgelogger.service ];then
        if [ ! -f /lib/systemd/system/edgelogger.service ];then
            cp /opt/IEF/Edge-logger/script/install/edgelogger.service /lib/systemd/system/
            systemctl enable edgelogger.service
            systemctl start edgelogger.service
            logger_Info "edgelogger start"
        fi
    fi
    if [ -f /opt/IEF/Edge-monitor/script/install/edgemonitor.service ];then
        if [ ! -f /lib/systemd/system/edgemonitor.service ];then
            cp /opt/IEF/Edge-monitor/script/install/edgemonitor.service /lib/systemd/system/
            systemctl enable edgemonitor.service
            systemctl start edgemonitor.service
            logger_Info "edgemonitor start"
        fi
    fi
}

function checkParams()
{
    local paramcnt=$#
    if [ $# -lt 1 ]; then
        logger_Info "take default settings."
        return 0
    fi
    
    for o in $*
    do
        case "$1" in
            -help)
                #show help
                if [ $paramcnt -ge 2 ];then
                    echo "Invalid input parameters"
                    showHelp
                    ret=1
                else
                    showHelp
                    ret=0
                fi
                exit "${ret}"
                ;;
            *)
                 [ -z "$1" ] && break
                 echo "Invalid input params."
                 return 1 
        esac
    done
    return 0
}

function main()
{
    local params="$@"
    
    checkParams "$@"
    if [ $? -ne 0 ]; then
        logger_Error "ERR: check params \"${params}\" failed."
        showHelp
        return 1
    fi
    
    prepareIEF
    start_IEF & 
    prepare
    startAtlasedge
    return 0
}

main "$@"

exit 0
